package com.order.model.sys;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;
import com.jfinal.ext.plugin.tablebind.TableBind;
import com.jfinal.kit.StringKit;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Page;
import com.order.shiro.ShiroUtils;
import com.order.utils.DateUtils;
import com.order.utils.JsonUtils;

@TableBind(tableName = "sys_user_role", pkName = "id")
public class SysUserRole extends Model<SysUserRole> {

	private static final long serialVersionUID = 1L;
	public static SysUserRole dao = new SysUserRole();
	public static final String ID = "id";
	public static final String SYS_USER_ID = "sys_user_id";
	public static final String SYS_ROLE_ID = "sys_role_id";
	public static final String LAST_UPDATED_BY = "last_updated_by";
	public static final String LAST_UPDATE_DATE = "last_update_date";
	public static String lastUpdatedUserName = "";
	
	public static String getLastUpdatedUserName() {
		return lastUpdatedUserName;
	}

	public static void setLastUpdatedUserName(String lastUpdatedUserName) {
		SysUserRole.lastUpdatedUserName = lastUpdatedUserName;
	}

	/** 
	* @Title: isAuthorizeRole 
	* @描述: 判断角色是否存在对应用户
	* @param userid
	* @return   
	* boolean    
	* @throws 
	*/ 
	public boolean isAuthorizeRole(int userid) {
		return dao.findFirst("select * from sys_user_role where sys_user_id = ?", userid) != null;
	}
	
	/** 
	* @Title: getRoleUser 
	* @描述: 查询用户角色
	* @param page
	* @param pagesize
	* @param roleid
	* @param jsonObj
	* @return   
	* Map<String,Object>    
	* @throws 
	*/ 
	public Map<String, Object> getRoleUser(int page,int pagesize,int roleid,JSONObject jsonObj) {
		String select = "select ur.id id, ur.last_updated_by, ur.last_update_date, "
				+ " u.id user_id, u.name user_name,"
				+ " r.id role_id,r.name role_name ";
		String sqlExceptSelect ="  from sys_user u, sys_role r, sys_user_role ur" 
								 +" where u.id = ur.sys_user_id " 
								 +"   and r.id = ur.sys_role_id ";
								 
		//角色ID
		if(0 < roleid){
			sqlExceptSelect += "   and ur.sys_role_id = "+roleid;
		}
		//用户名
		if(StringKit.notBlank(jsonObj.getString("USER_NAME"))){
			String username = jsonObj.getString("USER_NAME");
			sqlExceptSelect += "  and u.name like '%"+username+"%'";
		}		
		//角色名
		if(StringKit.notBlank(jsonObj.getString("ROLEN_AME"))){
			String email = jsonObj.getString("ROLE_NAME");
			sqlExceptSelect += "  and r.name like '%"+email+"%'";
		}    	
		Page<SysUserRole> list = dao.paginate(page, pagesize, select, sqlExceptSelect);
		//list = SysUserRole.findUpdatedUserName(list);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("Rows", list.getList());
		map.put("Total", list.getTotalRow());
		return map;
	}

	/** 
	* @Title: findUpdatedUserName 
	* @描述: 查找更新人姓名
	* @param list
	* @return   
	* Page<SysUserRole>    
	* @throws 
	*/ 
	private static Page<SysUserRole> findUpdatedUserName(Page<SysUserRole> list) {
		if(list == null || list.getList().isEmpty()){
			return list;
		}
		for(SysUserRole ur : list.getList()){
			System.out.println(ur);
			System.out.println(ur.get("last_updated_username").toString());
			lastUpdatedUserName = SysUser.dao.findById(ur.get("user_id")).get(SysUser.NAME);
			ur.set("last_updated_username", lastUpdatedUserName);
		}
		return list;
	}

	/** 
	* @Title: getObj 
	* @描述: json转对象
	* @param json   
	* void    
	* @throws 
	*/ 
	public SysUserRole getObj(String json) {
		try {
			return this.setAttrs(JsonUtils.fastjson2Map(json));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return this;
	}

	/** 
	* @Title: isContaintUR 
	* @描述: 判断是否存在角色-用户组合
	* @param userId
	* @param roleId
	* @return   
	* boolean    
	* @throws 
	*/ 
	public boolean isContaintUR(String userId, String roleId){
		String sql = "select count(1) row from sys_user_role ur "
				+ " where ur.sys_user_id = ? "
				+ " and ur.sys_role_id = ? ";
		int row = dao.findFirst(sql, userId, roleId).getNumber("row").intValue();
		if(row == 0){
			return false;
		}
		return true;
	}
	/** 
	* @Title: mySave 
	* @描述: 保存
	* @return   
	* boolean    
	* @throws 
	*/ 
	public String mySave() {
		String[] userIds = getStr(SYS_USER_ID).split(";");
		String roleId = getStr(SYS_ROLE_ID);
		String msg = "";
		for(String userId : userIds){
			if(isContaintUR(userId, roleId)){
				msg = "温馨提示：已存在角色-用户关系";
				return msg;
			}
			this.set(LAST_UPDATED_BY, ShiroUtils.getUserId())
			.set(LAST_UPDATE_DATE, DateUtils.getNowTime())
			.save();
			msg = "温馨提示：保存成功";
		}
		return msg;
	}

	 /** 
	* @Title: myUpdate 
	* @描述: 更新
	* @return   
	* String    
	* @throws 
	*/ 
	public String myUpdate(){
    	String msg = "";
    	String[] userids = getStr("SYS_USER_ID").split(";");
    	if(userids.length!=1){
    		msg = "温馨提示：修改失败，用户名修改需唯一";
    	}else{
	   	 	this.set(LAST_UPDATED_BY, ShiroUtils.getUserId());
	   	 	this.set(LAST_UPDATE_DATE, DateUtils.getNowTime());
	   	 	this.update();
	   	 	msg = "温馨提示：修改成功！";
    	}
   	 	return msg;
   }
}
